//
//  HSLoginController.swift
//  HomeSchoolDemo
//
//  Created by 张晓林 on 16/9/29.
//  Copyright © 2016年 张晓林. All rights reserved.
//

import UIKit
import SVProgressHUD

class HSLoginController: UIViewController {
    /// 账号输入框
    @IBOutlet fileprivate weak var loginAccountT: UITextField!
    /// 密码输入框
    @IBOutlet fileprivate weak var loginPasswordT: UITextField!
    /// 登录按钮属性
    @IBOutlet fileprivate weak var loginBtn: UIButton!
    /// 懒加载活动指示器
    lazy var activity:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 设置UI
        setupUI()
        
        // 添加活动指示器
        activity.center = view.center
        activity.color = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
        view.addSubview(activity)
        
    }
    
    // 设置UI
    fileprivate func setupUI() {
        // 设置圆角半径
        loginBtn.layer.cornerRadius = 5
        // 设置边框
        loginBtn.layer.borderColor = UIColor.gray.cgColor
        loginBtn.layer.borderWidth = 1
        // 设置输入框左边视图
        loginAccountT.leftView = setupLeftView(imageName: "icon_user")
        loginAccountT.leftViewMode = .always
        
        loginPasswordT.leftView = setupLeftView(imageName: "icon_password")
        loginPasswordT.leftViewMode = .always
    }
    
    // 左边视图
    fileprivate func setupLeftView(imageName: String) -> UIView {
        let bgView = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
        // 第一张图片视图
        let firstV = UIImageView(image: UIImage(named: imageName))
        firstV.center = CGPoint(x: firstV.bounds.width/2 + 10, y: 22)
        bgView.addSubview(firstV)
        // 第二张图片
        let towV = UIImageView(image: UIImage(named: "line_edit_sep"))
        towV.center = CGPoint(x: firstV.frame.maxX + towV.bounds.width/2 + 10, y: 22)
        bgView.addSubview(towV)
        
        return bgView
    }

    /// 登录按钮监听回调方法
    @IBAction func loginBtnClicked(_ sender: UIButton) {
        // 先要判断用是否已经设置服务器IP地址
        if baseURLStr == nil || baseURLStr! == "zao/interface/" {
            
            print("请先设置学校Ip地址")
            return
        }
        
        guard let acc = loginAccountT.text, acc != "" else {
            // 提醒用户账号不能为空
            SVProgressHUD.setMinimumDismissTimeInterval(2)
            SVProgressHUD.setDefaultStyle(.dark)
            SVProgressHUD.showInfo(withStatus: "账号不能为空")
            return
        }
        
        guard let pass = loginPasswordT.text, pass != "" else {
            SVProgressHUD.setMinimumDismissTimeInterval(2)
            SVProgressHUD.setDefaultStyle(.dark)
            SVProgressHUD.showInfo(withStatus: "密码不能为空")
            return
        }
        
        // 开启活动指示器
        activity.startAnimating()
        
        // 拼接地址
        let urlStr = baseURLStr! + "ZH-schoolname-S-login"
        // 参数字典
        let param = ["code":acc,"password":pass]
        // 请求数据
        HSNetworkTools.shared.downloadData(url: urlStr,
                                           parameters: param) {[weak self] (data, error) in
            
            // 到这里请求已经回调，关闭活动指示器
            self?.activity.stopAnimating()
            
            if error != nil {
                SVProgressHUD.setMinimumDismissTimeInterval(2)
                SVProgressHUD.setDefaultStyle(.dark)
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
                return
            }
            
            // 获得返回数据
            guard let dict = data as? NSDictionary else {
                return
            }
            // 将类型转换为Int
            let result = dict["result"] as! Int
            // 判断
            switch result {
            case 0:
                // 保存数据
                dict.write(toFile: saveUserInfoPath, atomically: true)
                // 跳转到下一个页面
                // 获得下一个页面控制器
                UIApplication.shared.keyWindow?.rootViewController = HSDrawerController()
                // 记录登录状态
                UserDefaults.standard.set(true, forKey: isLogin)
                
            case 1:
                SVProgressHUD.setMinimumDismissTimeInterval(2)
                SVProgressHUD.setDefaultStyle(.dark)
                SVProgressHUD.showInfo(withStatus: "账号或密码错误")
            default:
                break
            }
        }
    }
    
    /// 设置按钮监听回调方法
    @IBAction func loginSettingBtnClicked(_ sender: UIButton) {
        // 弹窗输入
        let alertVc = UIAlertController(title: "请输入学习服务器的IP地址",
                                        message: nil,
                                        preferredStyle: .alert)
        // 添加文本输入框
        alertVc.addTextField { (textF) in
            textF.placeholder = "Ip地址"
            textF.borderStyle = .none
            textF.textAlignment = .center
            // 获得保存的内容，显示
            let saveIp = UserDefaults.standard.value(forKey: xx_ipKey)
            textF.text = saveIp as? String
        }
        
        // 确定按钮
        alertVc.addAction(UIAlertAction(title: "确定", style: .default, handler: { (_) in
            print("确定按钮")
            // 获得输入框的内容
            let IPText = alertVc.textFields?[0].text
            // 保存字符串
            UserDefaults.standard.set(IPText, forKey: xx_ipKey)
        }))
        
        // 取消按钮
        alertVc.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        
        present(alertVc, animated: true, completion: nil)
    }
    
}


extension HSLoginController {
    
    /// 调整状态栏模式
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
    /// 回收键盘
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
}






